var moment = require('moment')
const db = require('../db')

const getUsers = (req, res) => {
  const sql = 'select * from users2 where isdel = 0'
  db.query(sql, [], (results, fields) => {
    let newsResults = results.map(item => {
      if (item.password) {
        delete item.password
      }
      return item
    })
    res.send({ status: 0, message: newsResults })
  })
}

const getUsersById = (req, res) => {
  const sql = 'select * from users2 where id = ?'
  const id = req.params.id
  db.query(sql, [id], results => {
    let newsResults = results.map(item => {
      if (item.password) {
        delete item.password
      }
      return item
    })
    if (results.length === 0) return res.send({ status: 2, message: '获取的用户不存在' })
    res.send({ status: 0, message: newsResults })
  })
}

const addUsers = (req, res) => {
  const sql = 'insert into users2 set ?'
  let body = req.body
  body.ctime = moment().format('YYYY-MM-DD hh:mm:ss')
  db.query(sql, [body], results => {
    if (results.affectedRows !== 1) return res.send({ status: 2, message: '添加数据失败' })
    res.send({ status: 0, message: '添加用户成功' })
  })
}

const updateUsers = (req, res) => {
  const sql = 'update users2 set ? where id = ?'
  const id = req.params.id
  let body = req.body
  body.ctime = moment().format('YYYY-MM-DD hh:mm:ss')
  db.query(sql, [body, id], results => {
    if (results.affectedRows !== 1) return res.send({ status: 2, message: '更新失败' })
    res.send({ status: 0, message: '更新成功' })
  })
}

const deleteUsers = (req, res) => {
  const id = req.params.id
  const sql = 'update users2 set isdel = 1 where id = ?'
  console.log(id)
  db.query(sql, [id], results => {
    console.log(results)
    if (results.affectedRows === 1) return res.send({ status: 2, message: '删除失败' })
    res.send({ status: 0, message: '删除成功' })
  })
}

module.exports = {
  getUsers,
  getUsersById,
  addUsers,
  updateUsers,
  deleteUsers
}